package com.web.exiaodao.remote.controller;

import com.web.exiaodao.business.entity.Moments;
import com.web.exiaodao.business.entity.MomentsInteraction;
import com.web.exiaodao.remote.service.ApiMomentsInteractionService;
import com.web.exiaodao.remote.service.ApiMomentsService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.MomentsInteractionVo;
import com.web.exiaodao.remote.vo.MomentsVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.ReflectionUtils;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiMomentsController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 朋友圈信息接口
 * @date 2016-11-10 14:29:16
 */
@Api(value = "Moments", description = "朋友圈(交流)接口", position = 10)
@Controller
@RequestMapping("/api/moments")
public class ApiMomentsController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiMomentsController.class);

    @Autowired
    private ApiMomentsService momentsService;
    @Autowired
    private ApiMomentsInteractionService momentsInteractionService;
    @Autowired
    private ApiUserService userService;

    /**
     * @return
     * @Title: findMomentsList
     * @Description: 查询所有朋友圈信息
     */
    @ApiOperation(value = "查询所有朋友圈", notes = "查询所有朋友圈信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findMomentsList", method = RequestMethod.POST)
    public XaResult<List<MomentsVo>> findMomentsList(
            @ApiParam("用户Id,字段名:userId;用来判断自己是否点赞") @RequestParam(value = "userId", required = false) Long userId,
            @ApiParam("查询的用户Id,字段名:searchUserId") @RequestParam(value = "searchUserId", required = false)  Long searchUserId,
            @ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0") Integer nextPage,
            @ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10") Integer pageSize
    ) throws BusinessException {
        XaResult<List<MomentsVo>> xr = new XaResult<>();
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{}", "search_");
        if (searchUserId != null) {
            filterParams = WebUitl.getParametersStartingWith("{'search_EQ_userId':'" + searchUserId + "'}", "search_");
        }
        //查询用户是否存在
        if (userId != null) {
            userService.findOne(userId);
        }
        xr = momentsService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable, NumberUtils.toLong(userId+""));
        return xr;
    }

    /**
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "发朋友圈", notes = "新增朋友圈,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "saveMoments", method = RequestMethod.POST)
    public XaResult<MomentsVo> saveMoments(
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("朋友圈内容,字段名:content") @RequestParam(value = "content", required = false) String content,
            @ApiParam("朋友圈图片,字段名:photos") @RequestParam(value = "photos", required = false) String photos,
            HttpServletRequest request
    ) throws Exception {
        XaResult<MomentsVo> xr = new XaResult<MomentsVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        if (!(XaUtil.isNotEmpty(content) || XaUtil.isNotEmpty(photos))) {
            xr.error("请填写内容或者上传图片！");
            return xr;
        }
        if (XaUtil.isNotEmpty(photos) && photos.split(",").length > 9) {
            xr.error("图片最多上传9张！");
            return xr;
        }
        //查询用户是否存在
        if (userId != null) {
            userService.findOne(userId);
        }

        Moments model = new Moments();
        model.setUserId(userId);
        model.setContent(content);
        model.setPhotos(photos);
        return momentsService.createModel(model);
    }

    /**
     * @param modelIds //@param status   操作类型:-1锁定,0无效,1正常,2发布,3删除,默认删除操作
     * @return
     * @Title: operateMomentsById
     * @Description: 操作一个实体状态, 根据status进行操作
     */
    @ApiOperation(value = "删除朋友圈", notes = "删除朋友圈,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "deleteMomentsById", method = RequestMethod.POST)
    public XaResult<MomentsVo> deleteMomentsById(
            HttpServletRequest request,
            @ApiParam("编号,字段名:modelIds,必填") @RequestParam(value = "momentId") String modelIds,
            @ApiParam("userId,字段名:userId,必填") @RequestParam(value = "userId") Long userId
    ) throws BusinessException {
        XaResult<MomentsVo> xr = new XaResult<MomentsVo>();
        //查询用户是否存在
        if (userId != null) {
            userService.findOne(userId);
        }

        return momentsService.deleteWorkGroup(modelIds, XaConstant.Status.delete, userId + "");
    }


    /**
     * saveWorkGroupInteraction
     *
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "点赞或评论", notes = "点赞或评论,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "saveMomentsInteraction", method = RequestMethod.POST)
    public XaResult<MomentsInteractionVo> saveMomentsInteraction(
            @ApiParam("用户Id,当前点赞或评论的用户id:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("朋友圈id,字段名:momentId") @RequestParam(value = "momentId") Long momentId,
            @ApiParam("类型,字段名:type，1：点赞、2：评论") @RequestParam(value = "type") Integer type,
            @ApiParam("回复人Id,字段名:replyToUserId，回复他人的评论时传") @RequestParam(value = "replyToUserId", required = false) Long replyToUserId,
            @ApiParam("内容,字段名:content，点赞时为空") @RequestParam(value = "content", required = false) String content,
            HttpServletRequest request
    ) throws Exception {
        XaResult<MomentsInteractionVo> xr = new XaResult<MomentsInteractionVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(momentId)) {
            xr.error("朋友圈Id不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(type)) {
            xr.error("类型不能为空！");
            return xr;
        }
        if (type != 1 && type != 2) {
            xr.error("错误的类型！");
            return xr;
        }
        if (type == 2) {
            if (XaUtil.isEmpty(content)) {
                xr.error("评论时内容不能为空！");
                return xr;
            }
            int length = ReflectionUtils.getHibernateColumnAnnotationLength(MomentsInteraction.class, "content");
            if (content.length() > length) {
                xr.error("评论内容不能超过" + length);
                return xr;
            }
        }
        if (replyToUserId != null && type == 2 && userId.intValue() == replyToUserId.intValue()) {
            xr.error("自己不能回复自己！");
            return xr;
        }

        //查询用户是否存在
        if (userId != null) {
            userService.findOne(userId);
        }
        if (replyToUserId != null) {
            userService.findOne(replyToUserId);
        }

        momentsService.findOne(momentId);

        //点赞:同一个人,同一条朋友圈只能点赞一次
        if (type == 1 && momentsInteractionService.isLike(userId + "", momentId).getObject()) {
            xr.error("你已经点赞,请不要重复点赞");
            return xr;
        }

        MomentsInteraction model = new MomentsInteraction();
        model.setMomentId(momentId + "");
        model.setType(type);
        model.setUserId(userId);
        model.setReplyToUserId(replyToUserId);
        model.setContent(content);
        return momentsInteractionService.createModel(model);
    }

    /**
     * @return
     * @Title: save
     * @Description: 取消点赞
     */
    @ApiOperation(value = "取消点赞", notes = "取消点赞,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "cancelLike", method = RequestMethod.POST)
    public XaResult<Boolean> cancelLike(
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("朋友圈id,字段名:momentId") @RequestParam(value = "momentId") Long momentId
    ) throws BusinessException {
        XaResult<Boolean> xr = new XaResult<>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(momentId)) {
            xr.error("朋友圈Id不能为空！");
            return xr;
        }
        xr = momentsInteractionService.cancelLike(userId + "", momentId);
        return xr;
    }

    /**
     * @return
     * @Title: operateTaskById
     * @Description: 操作一个实体状态, 根据status进行操作
     */
    @ApiOperation(value = "删除评论", notes = "删除评论,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "deleteMomentInteraction", method = RequestMethod.POST)
    public XaResult<MomentsInteractionVo> deleteMomentInteraction(
            HttpServletRequest request,
            @ApiParam("interactionId,字段名:interactionId,必填") @RequestParam(value = "interactionId") Long interactionId,
            @ApiParam("userId,字段名:userId,必填") @RequestParam(value = "userId") Long userId
    ) throws BusinessException {
        XaResult<MomentsInteractionVo> xr = new XaResult<>();
        xr = momentsInteractionService.deleteMomentInteraction(interactionId + "", XaConstant.Status.delete, userId + "");
        return xr;
    }
}

